#include "rbl_algo.h"
#if FUPDATE_USING_GZIP

#include <zlib.h>

void *rbl_gzip_decompress_context_create(void)
{
	void * gzip_decom_ctx  = rt_calloc(1, sizeof(z_stream));
  rt_memset((uint8_t *)gzip_decom_ctx, 0, sizeof(z_stream));
	inflateInit2(gzip_decom_ctx, 47);
	return gzip_decom_ctx;
}

void rbl_gzip_decompress_context_delete(void *gzip_decom_ctx)
{
	z_stream* z_stream_ctx = gzip_decom_ctx;
	inflateEnd(z_stream_ctx);
	rt_free(gzip_decom_ctx);
}

void rbl_gzip_decompress_set_in(void *gzip_decom_ctx, uint8_t *in_buf, uint32_t in_size)
{
	z_stream* z_stream_ctx = gzip_decom_ctx;
	z_stream_ctx->next_in = in_buf;
	z_stream_ctx->avail_in = in_size;
}

int rbl_gzip_decompress_data(void *gzip_decom_ctx, uint8_t *out_buf, uint32_t out_buf_size)
{
	int ret;
	z_stream* z_stream_ctx = gzip_decom_ctx;
	
	z_stream_ctx->next_out = out_buf;
	z_stream_ctx->avail_out = out_buf_size;

	ret = inflate(z_stream_ctx, Z_NO_FLUSH);
	switch (ret)
	{
		case Z_NEED_DICT:
		ret = Z_DATA_ERROR;
		case Z_DATA_ERROR:
		case Z_MEM_ERROR:
			inflateEnd(z_stream_ctx);
			return (ret);
	}
	return (out_buf_size - z_stream_ctx->avail_out);
}

#endif
